package cn.kgc.commons.util;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class UserContextHolder {
    private UserContextHolder(){
        threadLocal=new ThreadLocal<>();
    }

    private static  UserContextHolder userContextHolder = new UserContextHolder();

    public static UserContextHolder getInstance(){
        return userContextHolder;
    }

    //登录用户名
    public static final String LOGIN_USER_NAME="login_user_name";

    //登录用户ID
    public static final String LOGIN_USER_ID="login_user_id";


    //在同一个线程中,保存用户信息
    private ThreadLocal<Map<String,String>>  threadLocal;


    /**
     * 保存登录的用户名
     */
    public void setUserNameAndUserId(String username,String userId){
        Map<String,String> map=new HashMap<>();
        map.put(UserContextHolder.LOGIN_USER_NAME,username);
        map.put(UserContextHolder.LOGIN_USER_ID,userId);
        threadLocal.set(map);
    }

    /***
     * 获得用户名
     * @return
     */
    public String getUserName(){
        Map<String,String> map= threadLocal.get();
        if(map!=null && map.size()>0){
            return map.get(UserContextHolder.LOGIN_USER_NAME);
        }
        return null;
    }

    public String getUserId(){
        Map<String,String> map= threadLocal.get();
        if(map!=null && map.size()>0){
            return map.get(UserContextHolder.LOGIN_USER_ID);
        }
        return null;
    }

    //清除map中的数据
    public void clear(){
        threadLocal.set(null);
    }

}
